Adding Express Middlewares
Catalyst uses Express.js under the hood, allowing you to add custom middlewares in server/server.js.
The examples below use the ESM server contract in Catalyst 0.3.x. Legacy 0.2.x applications may
retain CommonJS imports until they upgrade.
Basic Setup
Export an addMiddlewares function that receives the Express app instance:
import express from "express";import path from "path";import expressStaticGzip from "express-static-gzip";export function addMiddlewares(app) {if (process.env.NODE_ENV === "production") {app.use(`${process.env.PUBLIC_STATIC_ASSET_PATH}/client`,expressStaticGzip(path.join(__dirname, `../${process.env.BUILD_OUTPUT_PATH}/client`),{enableBrotli: true,orderPreference: ["br", "gz"],serveStatic: { maxAge: "1y", etag: true },}));}app.use("/favicon.ico", express.static(path.join(__dirname, "../public/favicon.ico")));}
Examples
Serving Static Files
import express from "express";import path from "path";export function addMiddlewares(app) {app.use("/assets", express.static(path.join(__dirname, "../src/static")));app.use("/favicon.ico", express.static(path.join(__dirname, "../public/favicon.ico")));}
Adding Custom Headers
export function addMiddlewares(app) {app.use((req, res, next) => {res.setHeader("X-Custom-Header", "value");next();});}
Request Logging
import morgan from "morgan";export function addMiddlewares(app) {app.use(morgan("combined"));}
Authentication Middleware
export function addMiddlewares(app) {app.use((req, res, next) => {const token = req.headers.authorization;if (token) {req.user = verifyToken(token);}next();});}
Middleware Order
Middlewares execute in the order they are added. Place authentication and logging middlewares before route handlers:
export function addMiddlewares(app) {// 1. Logging (runs first)app.use(morgan("combined"));// 2. Static filesapp.use("/assets", express.static("./public"));// 3. Authenticationapp.use(authMiddleware);// 4. Custom headersapp.use(headerMiddleware);}